package org.daochong.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.daochong.lang.BeanUtil;
import org.daochong.lang.StringUtils;
import org.daochong.web.WebUtils;

public class AutoCSRFTokenFilter implements Filter {
	private String tokenId = "csrf_token";

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		filterChain.doFilter(req, resp);
		String method = request.getMethod();
		if (method.equals("GET")) {
			String type = response.getContentType();
			if (type != null) {
				if (type.toLowerCase().indexOf("text/html") >= 0) {
					String uri = request.getRequestURI();
					HttpSession session = request.getSession();
					session.setAttribute("SIGN_" + tokenId, StringUtils.md5(uri));
					String token = BeanUtil.uuid();
					session.setAttribute(tokenId, token);
					WebUtils.setCookies(tokenId, token, response);
				}
			}
		} else {

		}
		
	}

	public void init(FilterConfig config) throws ServletException {
		String str = config.getInitParameter("tokenId");
		if (str != null && str.length() > 0) {
			tokenId = str;
		}
	}

}
